layout = window.layout || {};
layout.mobile = true;
layout.desktop = layout;
var locate = window.location;
layout.protocol = locate.protocol;
var href = locate.href;
layout.session = layout.session || {};
if (href.indexOf("debugger") != -1) layout.debugger = true;
o2.addReady(function () {
    o2.load(["../o2_lib/mootools/plugin/mBox.Notice.js", "../o2_lib/mootools/plugin/mBox.Tooltip.js"], { "sequence": true }, function () {
        //MWF.defaultPath = "../x_desktop"+MWF.defaultPath;

        // 是否ip
        var _isIp = function(ip) {
            var reg = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/
            return reg.test(ip);
        };
        //修改支持x-token
        var uri = new URI(window.location.href);
        var options = uri.get("data");
        if (options[o2.tokenName]) {
            // 删除
            Cookie.dispose(o2.tokenName);
            // 写入
            var host = window.location.hostname; // 域名
            var domain = null;
            if (_isIp(host)) {
                domain = host;
            }else {
                if (host.indexOf(".") > 0) {
                    domain = host.substring(host.indexOf(".")); // 上级域名 如 .o2oa.net
                }
            }
            if (domain) {
                Cookie.write(o2.tokenName, options[o2.tokenName], {domain: domain, path:"/"});
            }else {
                Cookie.write(o2.tokenName, options[o2.tokenName]);
            }
        }

        MWF.loadLP("zh-cn");

        MWF.require("MWF.widget.Mask", null, false);
        layout.mask = new MWF.widget.Mask({ "style": "desktop" });
        layout.mask.load();

        MWF.require("MWF.xDesktop.Layout", function () {
            MWF.require("MWF.xDesktop.Authentication", null, false);
            MWF.require("MWF.xDesktop.Common", null, false);
            MWF.require("MWF.xAction.RestActions", null, false);

            (function () {
                layout.load = function () {
                    if (this.isAuthentication()) {
                        //var preview = window.frameElement.retrieve("preview");
                        //layout.desktop = window.frameElement.ownerDocument.window.layout.desktop;
                        //
                        this.node = $("layout");
                        this.content = $(document.body);
                        this.path = "../x_component_ForumDocument/$Mobile/";
                        this.cssPath = "../x_component_ForumDocument/$Mobile/default/css.wcss";
                        this._loadCss();

                        // MWF.require("MWF.xDesktop.MessageMobile", function(){
                        //     layout.message = new MWF.xDesktop.MessageMobile();
                        //     layout.message.load();
                        // }.bind(this));


                        // MWF.xDesktop.requireApp("Forum", "Actions.RestActions", null, false);
                        // this.action = new MWF.xApplication.Forum.Actions.RestActions();
                        this.action = MWF.Actions.get("x_bbs_assemble_control");
                        MWF.xDesktop.requireApp("Forum", "lp." + MWF.language, null, false);
                        //MWF.xDesktop.requireApp("Forum", "lp."+MWF.language, {
                        //    "onRequestFailure": function(){
                        //        MWF.xDesktop.requireApp("Forum", "lp.zh-cn", null, false);
                        //    }.bind(this),
                        //    "onSuccess": function(){}.bind(this)
                        //}, false);

                        this.lp = MWF.xApplication.Forum.LP;

                        this.options = this.getIds();
                        this.openForumDoc(this.options);

                        //MWF.require("MWF.xApplication.process.Xform.Form", function(){
                        //    layout.appForm = new MWF.APPForm($("layout"), preview.data);
                        //    layout.appForm.load();
                        //});
                    }
                };
                layout.close = function () {
                    $(document.body).addEvent("click", function () { window.close(); });
                };
                layout._loadCss = function () {
                    var key = encodeURIComponent(this.cssPath);
                    if (MWF.widget.css[key]) {
                        this.css = MWF.widget.css[key];
                    } else {
                        var r = new Request.JSON({
                            url: this.cssPath,
                            secure: false,
                            async: false,
                            method: "get",
                            noCache: false,
                            onSuccess: function (responseJSON, responseText) {
                                this.css = responseJSON;
                                MWF.widget.css[key] = responseJSON;
                            }.bind(this),
                            onError: function (text, error) {
                                alert(error + text);
                            }
                        });
                        r.send();
                    }
                };
                //layout.message = {
                //    "node": (function(){
                //        var node = new Element("div", {
                //            "styles": {
                //                "width": "100%",
                //                "position": "absolute",
                //                "top": "0px",
                //                "left": "0px",
                //                "background-color": "#FFF",
                //                "overflow": "hidden"
                //            }
                //        }).inject($(document.body));
                //        return node
                //    })(),
                //
                //    addMessage: function(msg){
                //        var subjectNode = new Element("div", {
                //            "styles": {
                //                "margin": "0px 10px",
                //                "height": "20px",
                //                "line-height": "20px",
                //                "font-size": "14px",
                //                "color": "#4387cd"
                //            }
                //        }).inject(this.node);
                //        var contentNode = new Element("div", {
                //            "styles": {
                //                "width": "100%",
                //                "position": "absolute",
                //                "top": "0px",
                //                "left": "0px",
                //                "background-color": "#FFF",
                //                "overflow": "hidden"
                //            }
                //        }).inject(this.node);
                //    }
                //
                //},
                layout.getIds = function () {

                    var href = window.location.href;
                    var qStr = href.substr(href.indexOf("?") + 1, href.length);
                    var qDatas = qStr.split("&");
                    var obj = {};
                    qDatas.each(function (d) {
                        var q = d.split("=");
                        obj[q[0].toLowerCase()] = q[1];
                    });

                    return obj;
                };
                layout.errorWork = function () {
                    if (this.mask) this.mask.hide();
                    this.node.set("text", "openError");
                };
                layout.openForumDoc = function () {
                    MWF.xDesktop.requireApp("ForumDocument", "Mobile", function () {
                        this.forumDoc = new MWF.xApplication.ForumDocument.Mobile(this.node, this, this.action, this.lp, this.css, {
                            id: this.options.id,
                            viewPageNum: this.options.page
                        });
                        this.forumDoc.load();
                        if (this.mask) this.mask.hide();
                    }.bind(this));
                };

                layout.showReply = function (id) {
                    this.forumDoc.showReply(id);
                };

                layout.isAuthentication = function () {
                    layout.authentication = new MWF.xDesktop.Authentication({
                        "onLogin": layout.load.bind(layout)
                    });

                    var returnValue = true;
                    this.authentication.isAuthenticated(function (json) {
                        this.user = json.data;
                        layout.session.user = json.data;
                    }.bind(this), function () {
                        this.authentication.loadLogin(this.node);
                        returnValue = false;
                    }.bind(this));
                    return returnValue;
                };
                //layout.getServiceAddress = function(callback){
                //    var host = layout.config.center.host || window.location.hostname;
                //    var port = layout.config.center.port;
                //    var uri = "";
                //    if (!port || port=="80"){
                //        uri = "http://"+host+"/x_program_center/jaxrs/distribute/assemble/source/{source}";
                //    }else{
                //        uri = "http://"+host+":"+port+"/x_program_center/jaxrs/distribute/assemble/source/{source}";
                //    }
                //    var currenthost = window.location.hostname;
                //    uri = uri.replace(/{source}/g, currenthost);
                //    //var uri = "http://"+layout.config.center+"/x_program_center/jaxrs/distribute/assemble";
                //    MWF.restful("get", uri, null, function(json){
                //        this.serviceAddressList = json.data;
                //        if (callback) callback();
                //    }.bind(this));
                //};
                //layout.getServiceAddress = function(callback){
                //    if (typeOf(layout.config.center)=="object"){
                //        this.getServiceAddressConfigObject(callback);
                //    }else if (typeOf(layout.config.center)=="array"){
                //        this.getServiceAddressConfigArray(callback);
                //    }
                //
                //};
                //layout.getServiceAddressConfigArray = function(callback) {
                //    var requests = [];
                //    layout.config.center.each(function(center){
                //        requests.push(
                //            this.getServiceAddressConfigObject(function(){
                //                requests.each(function(res){
                //                    if (res.isRunning()){res.cancel();}
                //                });
                //                if (callback) callback();
                //            }.bind(this), center)
                //        );
                //    }.bind(this));
                //};
                //layout.getServiceAddressConfigObject = function(callback, center){
                //    var centerConfig = center;
                //    if (!centerConfig) centerConfig = layout.config.center;
                //    var host = centerConfig.host || window.location.hostname;
                //    var port = centerConfig.port;
                //    var uri = "";
                //    if (!port || port=="80"){
                //        uri = "http://"+host+"/x_program_center/jaxrs/distribute/assemble/source/{source}";
                //    }else{
                //        uri = "http://"+host+":"+port+"/x_program_center/jaxrs/distribute/assemble/source/{source}";
                //    }
                //    var currenthost = window.location.hostname;
                //    uri = uri.replace(/{source}/g, currenthost);
                //    //var uri = "http://"+layout.config.center+"/x_program_center/jaxrs/distribute/assemble";
                //    return MWF.restful("get", uri, null, function(json){
                //        this.serviceAddressList = json.data;
                //        this.centerServer = center;
                //        if (callback) callback();
                //    }.bind(this));
                //};
                layout.confirm = function (type, e, title, text, width, height, ok, cancel, callback, mask, style) {
                    MWF.require("MWF.xDesktop.Dialog", function () {
                        var size = this.content.getSize();
                        var x = 0;
                        var y = 0;
                        if (typeOf(e) == "element") {
                            var position = e.getPosition(this.content);
                            x = position.x;
                            y = position.y;
                        } else {
                            if (Browser.name == "firefox") {
                                x = parseFloat(e.event.clientX);
                                y = parseFloat(e.event.clientY);
                            } else {
                                x = parseFloat(e.event.x);
                                y = parseFloat(e.event.y);
                            }


                            //    if (!x || !y){
                            if (e.target) {
                                var position = e.target.getPosition(this.content);
                                x = position.x;
                                y = position.y;
                            }
                            //    }
                        }

                        if (x + parseFloat(width) > size.x) {
                            x = x - parseFloat(width);
                        }
                        if (x < 0) x = 0;
                        if (y + parseFloat(height) > size.y) {
                            y = y - parseFloat(height);
                        }
                        if (y < 0) y = 0;

                        var ctext = "";
                        var chtml = "";
                        if (typeOf(text).toLowerCase() == "object") {
                            ctext = text.text;
                            chtml = text.html;
                        } else {
                            ctext = text;
                        }
                        var dlg = new MWF.xDesktop.Dialog({
                            "title": title,
                            "style": style || "flat",
                            "top": y,
                            "left": x - 20,
                            "fromTop": y,
                            "fromLeft": x - 20,
                            "width": width,
                            "height": height,
                            "text": ctext,
                            "html": chtml,
                            "container": this.content,
                            "maskNode": mask,
                            "buttonList": [
                                {
                                    "text": MWF.LP.process.button.ok,
                                    "action": ok
                                },
                                {
                                    "text": MWF.LP.process.button.cancel,
                                    "action": cancel
                                }
                            ]
                        });

                        switch (type.toLowerCase()) {
                            case "success":
                                dlg.content.setStyle("background-image", "url()");
                                break;
                            case "error":
                                dlg.content.setStyle("background-image", "url()");
                                break;
                            case "info":
                                dlg.content.setStyle("background-image", "url()");
                                break;
                            case "warn":
                                dlg.content.setStyle("background-image", "url()");
                                break;
                            default:
                            //dlg.content.setStyle("background-image", "");
                        }
                        dlg.show();
                        if (callback) callback(dlg);
                    }.bind(this));
                };
                layout.notice = function (content, type, target, where, offset) {
                    if (!where) where = { "x": "right", "y": "top" };
                    if (!target) target = this.content;
                    if (!type) type = "ok";
                    var noticeTarget = target || $(document.body);
                    var off = offset;
                    if (!off) {
                        off = {
                            x: 10,
                            y: where.y.toString().toLowerCase() == "bottom" ? 10 : 10
                        };
                    }

                    new mBox.Notice({
                        type: type,
                        position: where,
                        move: false,
                        target: noticeTarget,
                        delayClose: (type == "error") ? 10000 : 5000,
                        offset: off,
                        content: content
                    });
                };
                layout.reload = function () {
                    window.location.reload();
                };
                layout.openApplication = function () {

                };

                MWF.getJSON("res/config/config.json", function (config) {
                    if (config.proxyCenterEnable){
                        if (o2.typeOf(config.center)==="array"){
                            config.center.forEach(function(c){
                                c.port = window.location.port || 80;
                            });
                        }else{
                            config.port = window.location.port || 80;
                        }
                    }
                    layout.config = config;
                    o2.tokenName = config.tokenName || "x-token";
                    MWF.xDesktop.getServiceAddress(layout.config, function (service, center) {
                        layout.serviceAddressList = service;
                        layout.centerServer = center;
                        layout.load();
                    }.bind(this));
                    //layout.getServiceAddress(function(){
                    //    layout.load();
                    //});
                });
            })();

        });
    });
});
